package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dto.EmailInfo;
import cd.cdyb.sms.service.EmailService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("emailService")
public class EmailServiceImpl implements EmailService {


    @Value("${mail.from}")
    private String from;

    @Value("${mail.authorization_code}")
    private String authorization_code;

    @Value("${mail.send_port}")
    private Integer send_port;

    @Value("${mail.send_server}")
    private String send_server;

    @Value("${mail.send_name}")
    private String send_name;

    /**
     * 获取邮箱参数对象
     *
     * @param emailInfo
     * @return
     */
    private static MailAccount getMailAccount(EmailInfo emailInfo) {
        MailAccount account = new MailAccount();

        if (ObjectUtil.isNotEmpty(emailInfo.getSenderName())) {
            StringBuilder sb = new StringBuilder();
            sb.append(emailInfo.getSenderName())
                    .append('<')
                    .append(emailInfo.getEmailAccount())
                    .append('>');
            account.setFrom(sb.toString());
        } else {
            account.setFrom(emailInfo.getEmailAccount());
            account.setUser(emailInfo.getEmailToAccount());
        }
        account.setPass(emailInfo.getEmailPassword());
        account.setHost(emailInfo.getSendServer());
        account.setPort(emailInfo.getSendPort());
        account.setAuth(true);
        account.setSocketFactoryClass("javax.net.ssl.SSLSocketFactory");
        account.setSocketFactoryFallback(true);
        account.setSocketFactoryPort(emailInfo.getSendPort());
        if (emailInfo.getSendServerIsSSL() == 0) {
            account.setSslEnable(false);
        } else {
            account.setSslEnable(true);
        }
        account.setTimeout(3000);
        return account;
    }

    @Override
    public void sendEmail(String to, String subject, String content) {
        EmailInfo info = new EmailInfo();
        info.setEmailAccount(from);
        info.setEmailPassword(authorization_code);
        info.setSendPort(send_port);
        info.setSendServer(send_server); //遵循stmp的服务协议的服务器，可以百度，很多的
        info.setSenderName(send_name);
        info.setSendServerIsSSL(1);
        MailAccount account = getMailAccount(info);
        MailUtil.send(account, to, subject, content, false);
    }


}
